package com.huawei.demo;

import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.gaussdb.v3.GaussDBClient;
import com.huaweicloud.sdk.gaussdb.v3.model.AddDatabasePermissionRequest;
import com.huaweicloud.sdk.gaussdb.v3.model.AddDatabasePermissionResponse;
import com.huaweicloud.sdk.gaussdb.v3.model.CreateGaussMySqlDatabase;
import com.huaweicloud.sdk.gaussdb.v3.model.CreateGaussMySqlDatabaseRequest;
import com.huaweicloud.sdk.gaussdb.v3.model.CreateGaussMySqlDatabaseRequestBody;
import com.huaweicloud.sdk.gaussdb.v3.model.CreateGaussMySqlDatabaseResponse;
import com.huaweicloud.sdk.gaussdb.v3.model.DatabasePermission;
import com.huaweicloud.sdk.gaussdb.v3.model.GrantDatabasePermission;
import com.huaweicloud.sdk.gaussdb.v3.model.GrantDatabasePermissionRequestBody;
import com.huaweicloud.sdk.gaussdb.v3.model.ListGaussMySqlDatabaseRequest;
import com.huaweicloud.sdk.gaussdb.v3.model.ListGaussMySqlDatabaseResponse;
import com.huaweicloud.sdk.gaussdb.v3.model.ListGaussMySqlDatabaseUserRequest;
import com.huaweicloud.sdk.gaussdb.v3.model.ListGaussMySqlDatabaseUserResponse;
import com.huaweicloud.sdk.gaussdb.v3.region.GaussDBRegion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class DatabaseDemo {
    private static final Logger logger = LoggerFactory.getLogger(DatabaseDemo.class.getName());

    public static void main(String[] args) {
        String ak = "<YOUR AK>";
        String sk = "<YOUR SK>";
        String instanceId = "<YOUR INSTANCE_ID>";
        String regionId = "<YOUR REGION_ID>";

        ICredential auth = new BasicCredentials()
                .withAk(ak)
                .withSk(sk);

        GaussDBClient client = GaussDBClient.newBuilder()
                .withCredential(auth)
                .withRegion(GaussDBRegion.valueOf(regionId))
                .build();

        // 查询数据库列表
        listDatabases(client, instanceId);

        // 创建数据库的名称和字符集
        String dbName = "<YOUR DATABASE_NAME>";
        String dbCharacterSet = "<YOUR DATABASE_CHARACTERSET>";
        // 创建数据库
        createDatabase(client, instanceId, dbName, dbCharacterSet);

        // 查看用户列表
        ListGaussMySqlDatabaseUserResponse listGaussMySqlDatabaseUserResponse = listDatabaseUsers(client, instanceId);

        if (listGaussMySqlDatabaseUserResponse != null) {
            // 查询数据库用户的结果取第一个数据库用户进行授权
            String userName = listGaussMySqlDatabaseUserResponse.getUsers().get(0).getName();
            String host = listGaussMySqlDatabaseUserResponse.getUsers().get(0).getHost();
            // 授权数据库用户,只读选项取值为true或者false,这里以false为例
            boolean readonly = false;
            addDatabasePermission(client, instanceId, userName, host, dbName, readonly);
        }

    }

    private static void listDatabases(GaussDBClient client, String instanceId) {
        ListGaussMySqlDatabaseRequest request = new ListGaussMySqlDatabaseRequest();
        request.withInstanceId(instanceId);
        try {
            ListGaussMySqlDatabaseResponse response = client.listGaussMySqlDatabase(request);
            logger.info(response.toString());
        } catch (ConnectionException e) {
            logger.error("ConnectionException", e);
        } catch (RequestTimeoutException e) {
            logger.error("RequestTimeoutException ", e);
        } catch (ServiceResponseException e) {
            logger.error("httpStatusCode: {}, errorCode: {}, errorMsg: {}", e.getHttpStatusCode(), e.getErrorCode(), e.getErrorMsg());
        }
    }

    private static void createDatabase(GaussDBClient client, String instanceId, String dbName, String dbCharacterSet) {
        CreateGaussMySqlDatabaseRequest request = new CreateGaussMySqlDatabaseRequest();
        CreateGaussMySqlDatabaseRequestBody body = new CreateGaussMySqlDatabaseRequestBody();
        body.withDatabases(Collections.singletonList(new CreateGaussMySqlDatabase()
                .withName(dbName)
                .withCharacterSet(dbCharacterSet)));
        request.withInstanceId(instanceId)
                .withBody(body);
        try {
            CreateGaussMySqlDatabaseResponse response = client.createGaussMySqlDatabase(request);
            logger.info(response.toString());
        } catch (ConnectionException e) {
            logger.error("ConnectionException", e);
        } catch (RequestTimeoutException e) {
            logger.error("RequestTimeoutException ", e);
        } catch (ServiceResponseException e) {
            logger.error("httpStatusCode: {}, errorCode: {}, errorMsg: {}", e.getHttpStatusCode(), e.getErrorCode(), e.getErrorMsg());
        }

    }

    private static ListGaussMySqlDatabaseUserResponse listDatabaseUsers(GaussDBClient client, String instanceId) {
        ListGaussMySqlDatabaseUserRequest request = new ListGaussMySqlDatabaseUserRequest();
        request.withInstanceId(instanceId);
        try {
            ListGaussMySqlDatabaseUserResponse response = client.listGaussMySqlDatabaseUser(request);
            logger.info(response.toString());
            return response;
        } catch (ConnectionException e) {
            logger.error("ConnectionException", e);
        } catch (RequestTimeoutException e) {
            logger.error("RequestTimeoutException ", e);
        } catch (ServiceResponseException e) {
            logger.error("httpStatusCode: {}, errorCode: {}, errorMsg: {}", e.getHttpStatusCode(), e.getErrorCode(), e.getErrorMsg());
        }
        return null;
    }

    private static void addDatabasePermission(GaussDBClient client, String instanceId, String userName, String host, String dbName, boolean readonly) {
        AddDatabasePermissionRequest request = new AddDatabasePermissionRequest();
        request.withInstanceId(instanceId);
        GrantDatabasePermissionRequestBody body = new GrantDatabasePermissionRequestBody();
        List<DatabasePermission> databases = new ArrayList<>();
        databases.add(new DatabasePermission()
                .withName(dbName)
                .withReadonly(false));
        GrantDatabasePermission grantDatabasePermission = new GrantDatabasePermission()
                .withName(userName)
                .withHost(host)
                .withDatabases(databases);
        List<GrantDatabasePermission> grantDatabasePermissonList = new ArrayList<>();
        grantDatabasePermissonList.add(grantDatabasePermission);
        body.withUsers(grantDatabasePermissonList);
        request.withBody(body);
        try {
            AddDatabasePermissionResponse response = client.addDatabasePermission(request);
            logger.info(response.toString());
        } catch (ConnectionException e) {
            logger.error("ConnectionException", e);
        } catch (RequestTimeoutException e) {
            logger.error("RequestTimeoutException ", e);
        } catch (ServiceResponseException e) {
            logger.error("httpStatusCode: {}, errorCode: {}, errorMsg: {}", e.getHttpStatusCode(), e.getErrorCode(), e.getErrorMsg());
        }
    }

}
